package me.alex.lifecycledemo;

import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleEventObserver;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.OnLifecycleEvent;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * ================================================
 * Description:
 * <p>
 * Created by Alex on 2021/12/30
 * <p>
 * 页面内容介绍: 模拟业务发送或者接收,初始化后每秒log一次
 * 便于区分生命周期使用log.i   运行使用log.e
 * <p>
 * ================================================
 */
public class Lifecycle2 implements LifecycleEventObserver {
    private static final String TAG = Lifecycle2.class.getSimpleName();
    Disposable dis;
    boolean isRun = true;//是否运行  页面暂停的时候不log

    @Override
    public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
        Log.i(TAG, "onStateChanged:" + source.getLifecycle().getCurrentState());
        switch (event) {
            case ON_ANY:
                //通过这种方法是不会回调any的
                Log.i(TAG, "ON_ANY --- " + source.getLifecycle().getCurrentState());
                break;
            case ON_CREATE:
                Log.i(TAG, "ON_CREATE");
                dis = Observable.interval(3, TimeUnit.SECONDS)
                        .subscribe(new Consumer<Long>() {
                            @Override
                            public void accept(Long aLong) throws Exception {
                                if (isRun) {
                                    Log.e(TAG, "模拟运行,每3秒一次");
                                }
                            }
                        });
                break;
            case ON_START:
                Log.i(TAG, "ON_START");
                break;
            case ON_RESUME:
                Log.i(TAG, "ON_RESUME");
                break;
            case ON_PAUSE:
                Log.i(TAG, "ON_PAUSE");
                break;
            case ON_STOP:
                Log.i(TAG, "ON_STOP");
                break;
            case ON_DESTROY:
                Log.i(TAG, "ON_DESTROY");
                if (dis != null) {
                    dis.dispose();
                    Log.i(TAG, "串口关闭");
                }
                break;
        }
    }
}
